package com.jiangnan.warehouse_management.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    // 固定密钥
    private static final String SECRET_KEY = "warehouse-management-secret";
    // token过期时间：12小时
    private static final long EXPIRE_TIME = 1000 * 60 * 60 * 12;

    // 使用ThreadLocal存储当前用户信息
    private static final ThreadLocal<CurrentUser> currentUser = new ThreadLocal<>();

    @Data
    public static class CurrentUser {
        private Integer userId;
        private String username;
        private String role;
    }

    /**
     * 生成JWT令牌
     * @param userId 用户ID
     * @param username 用户名
     * @return JWT令牌
     */
    public static String generateToken(Integer userId, String username, String role) {
        return JWT.create()
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("role", role)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 验证JWT令牌
     * @param token JWT令牌
     * @return 是否有效
     */
    public static boolean validateToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY))
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            
            // 验证成功后，将用户信息存储到ThreadLocal中
            CurrentUser user = new CurrentUser();
            user.setUserId(jwt.getClaim("userId").asInt());
            user.setUsername(jwt.getClaim("username").asString());
            user.setRole(jwt.getClaim("role").toString());
            currentUser.set(user);
            
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 从token中获取用户ID
     * @param token JWT令牌
     * @return 用户ID
     */
    public static Integer getUserIdFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asInt();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从token中获取用户名
     * @param token JWT令牌
     * @return 用户名
     */
    public static String getUsernameFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户信息
     * @return 当前用户信息
     */
    public static CurrentUser getCurrentUser() {
        return currentUser.get();
    }

    /**
     * 清除当前用户信息
     */
    public static void clearCurrentUser() {
        currentUser.remove();
    }

    /**
     * 解析JWT令牌
     * @param token JWT令牌
     * @return 业务数据
     */
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET_KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }
}